<template>
  <div :class="{'cantEdit':!isEdit,'upload-ct': true }">
    <!-- action="http://macro-oss.oss-cn-shenzhen.aliyuncs.com" -->
    <el-upload
      :auto-upload="false"
      action
      :data="dataObj"
      list-type="picture"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="initfileList"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :on-change="changeImg"
    >
      <el-button size="small" type="primary" v-if="isEdit">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">{{ hint }}</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" :modal="isEdit">
      <img width="100%" :src="showImgUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getBase64,
  getUrlBase64,
  verifyImgType,
  fileLengthFormat
} from '@/utils/com'

export default {
  name: 'SingleUpload',
  props: {
    value: {
      type: String,
      default: null
    },
    hint: {
      type: String,
      default: ''
    },
    imgType: {
      type: Array,
      default: () => {
        return ['png', 'jpg', 'jpeg']
      }
    },
    maxSize: {
      type: Number,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dataObj: {},
      dialogVisible: false,
      showImgUrl: '',
      fileArr: [],
      base64: '',
      base64Name: '',
      imageUrl: ''
    }
  },
  computed: {
    ...mapGetters(['ossUrl']),
    // imageUrl() {
    //   console.log('changeImg', this.value)
    //   var ossUrl = '/oss' + this.value
    //   // 判断是base64的value
    //   if (this.value) {
    //     if (!(this.value.substring(0, 4) === 'data')) {
    //       getUrlBase64(ossUrl).then(res => {
    //         this.base64 = res
    //         this.emitInput(res)
    //         this.base64Name = ossUrl.substr(ossUrl.lastIndexOf('/') + 1)
    //       })
    //       return this.base64
    //     } else {
    //       return this.value
    //     }
    //   } else {
    //     return null
    //   }
    // },
    imageName() {
      if (this.value !== null && this.value !== '') {
        // 判断是base64的value，则返回文件名
        if (this.value.substring(0, 4) === 'data') {
          return this.base64Name.length > 0
            ? this.base64Name
            : this.fileArr.length > 0
            ? this.fileArr[0].raw.name
            : ''
        } else {
          return this.value.substr(this.value.lastIndexOf('/') + 1)
        }
      } else {
        return null
      }
    },
    showFileList: {
      get: function() {
        return this.value ? true : false
      },
      set: function(newValue) {}
    },
    initfileList: function() {
      var defaultImg = [
        {
          name: this.imageName,
          url: this.imageUrl
        }
      ]
      this.fileArr = defaultImg
      return defaultImg
    }
  },
  watch: {
    value() {
      console.log('changeImg', this.value)
      var ossUrl = '/oss' + this.value
      // 判断是base64的value
      if (this.value) {
        if (!(this.value.substring(0, 4) === 'data')) {
          getUrlBase64(ossUrl).then(res => {
            this.base64 = res
            this.emitInput(res)
            this.base64Name = ossUrl.substr(ossUrl.lastIndexOf('/') + 1)
          })
          this.imageUrl = this.base64
        } else {
          this.imageUrl = this.value
        }
      } else {
        this.imageUrl = null
      }
    }
  },
  methods: {
    emitInput(val) {
      this.$emit('input', val)
    },
    handleRemove(file, fileList) {
      this.fileArr.length = 0
      this.emitInput('')
      // this.fileArr.push(file)
      // this.$message({
      //   message: '删除失败，图片不能为空，请重新选择',
      //   type: 'error',
      //   duration: 3000
      // })
    },
    handlePreview(file) {
      this.dialogVisible = true
      this.showImgUrl = file.url
    },
    changeImg(file, fileList) {
      verifyImgType(file, this.imgType).then(res => {
        if (res.result === false) {
          var beforeImg = this.fileArr[0]
          this.fileArr.length = 0
          this.fileArr.push(beforeImg)

          this.$message({
            message: res.msg,
            type: 'error',
            duration: 3000
          })
        } else {
          if (this.maxSize) {
            const fileLength = (file.size / 1024 / 1024).toFixed(2)
            if (fileLength <= this.maxSize) {
              this.fileArr.length = 0
              this.fileArr.push(file)

              getBase64(file.raw).then(res => {
                this.emitInput(res)
              })
            } else {
              fileList.splice(fileList.length - 1, 1)
              this.$message({
                message:
                  '上传图片大小超过' +
                  this.maxSize +
                  'M，此图片大小为' +
                  fileLength +
                  '，请重新选择图片',
                type: 'error',
                duration: 3000
              })
            }
          } else {
            this.fileArr.length = 0
            this.fileArr.push(file)
            getBase64(file.raw).then(res => {
              this.emitInput(res)
            })
          }
        }
      })
    }
  }
}
</script>
<style scoped>
.upload-ct div {
  line-height: 0;
}
div.el-upload__tip {
  line-height: 20px;
}
</style>